<script setup lang='ts'>
import { useBatchSyncOrg, useGetJcOrgDataSource } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import XEUtils from 'xe-utils'

const enterpriseTypeOptions = defineModel<any>('enterpriseTypeOptions')

const treeSelect = defineModel<any>('treeSelect')

const tableRef = ref()

const { isPending, mutate } = useBatchSyncOrg()

const { data: OrgDataSourceData } = useGetJcOrgDataSource()

const treeData = ref<any[]>([])

const id = defineModel<any>('id')

const visible = defineModel<boolean>('visible', { required: true })

const dialog = '批量组织同步'

const formRef = ref()

const initialState = {
    parentCode: '',
}

const state = ref<any>(cloneDeep(initialState))

const columns: any[] = [
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            filterable: true,
            props: {
                checkStrictly: true,
                children: 'childs',
                emitPath: false,
                label: 'orgName',
                value: 'orgCode',
            },
            showAllLevels: false,
        },
        label: '关联上级组织',
        options: treeSelect,
        prop: 'parentCode',
        valueType: 'cascader',
    },
    {
        colProps: {
            span: 12,
        },
        label: '单位类型',
        options: enterpriseTypeOptions,
        prop: 'unitType',
        valueType: 'select',
    },
    {
        hasLabel: false,
        label: '关联上级组织',
        prop: 'a2',
    },
]

const rules = {
    parentCode: [
        {
            message: '请选择关联上级组织',
            required: true,
        },
    ],
    unitType: [
        {
            message: '请选择单位类型',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],

}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
    state.value = cloneDeep(initialState)
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const $table = tableRef.value
        if ($table) {
            const result = treeData.value.filter(item => item.isChecked)
            const orgList = XEUtils.toArrayTree(result, { key: 'ZZ_ZZBM', parentKey: 'ZZ_SJZZ' })
            const params = {
                orgList,
                parentCode: state.value.parentCode,
                unitType: state.value.unitType,
            }
            mutate(params, {
                onSuccess: () => {
                    ElMessage.success('操作成功')
                    cancel()
                },
            })
        }
    }
}

function handleCheckboxChange({ checked, row }) {
    const $table = tableRef.value
    const father = $table.getCheckboxIndeterminateRecords(true).filter((item: any) => item.syncStatus === 0)
    if (father.length) {
        father.forEach((item: any) => {
            item.isChecked = true
        })
    }

    formatCheckList([row], checked)
}

function formatCheckList(data: any[], checked: boolean) {
    data.forEach((item: any) => {
        if (item.syncStatus === 0)
            item.isChecked = checked

        if (item?.children && item?.children.length) {
            formatCheckList(item?.children, checked)
        }
    })
}

function isRowDisabled(row: any) {
    if (row.syncStatus === 0) {
        return true
    }
    if (row.children && row.children.length > 0) {
        row.children.some((child: any) => isRowDisabled(child))
    }
    return false
}

function checkMethod({ row }) {
    // 如果当前行的 disabled 字段为 true，或者任何子节点的 disabled 字段为 true，则禁用该行的勾选
    return isRowDisabled(row)
}

watchEffect(() => {
    if (OrgDataSourceData.value) {
        const result = cloneDeep(OrgDataSourceData.value)
        result.forEach((item: any) => {
            item.isChecked = false
        })
        treeData.value = result
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialog"
                width="1000"
                @cancel="cancel"
                @closed="reset"
    >
        <PlusForm ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="130"
                  :has-footer="false"
                  :row-props="{ gutter: 20 }"
                  :rules="rules"
        >
            <template #plus-field-a2>
                <vxe-table ref="tableRef"
                           :column-config="{ resizable: true }"
                           :tree-config="{ transform: true, rowField: 'ZZ_ZZBM', parentField: 'ZZ_SJZZ' }"
                           :checkbox-config="{ labelField: 'ZZ_ZZBM', checkMethod }"
                           :data="treeData"
                           height="400"
                           align="center"
                           show-overflow
                           :tooltip-config="{ zIndex: 9999 }"
                           border
                           class="w-full"
                           @checkbox-change="handleCheckboxChange"
                >
                    <vxe-column type="checkbox"
                                title="ID"
                                tree-node
                                width="250"
                    />

                    <vxe-column field="ZZ_ZZQC"
                                title="组织全称"
                    />

                    <vxe-column field="ZZ_ZZLB"
                                title="组织类别"
                    />

                    <vxe-column field="ZZ_ZZBM"
                                title="组织编码"
                    />

                    <vxe-column field="ZZ_ZZZT"
                                title="组织状态"
                    />

                    <vxe-column title="同步状态">
                        <template #default="{ row }">
                            {{ row?.syncStatus === 0 ? '未同步' : '已同步' }}
                        </template>
                    </vxe-column>
                </vxe-table>
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
